package cat200;

import javax.swing.*;

import java.text.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import java.util.Calendar;
import java.util.GregorianCalendar;  
/**
 *
 * @author peichia
 */
public class deposit1 extends javax.swing.JFrame {
	
	Timer timer = new Timer (4000, new TimerListener());
	
	private static String dbURL = "jdbc:derby://localhost:1527/sample;create=true;user=app;password=app";   
    private static Connection conn = null;
    private static Statement stmt = null;
    DecimalFormat dp = new DecimalFormat("#0.00");
    
    private static boolean isMember = false;
    private static Double totalAmt = 0.00;
    private static String Amt = "";
    private static Double depo = 0.00;
    
    private static int invNum = 0;

    /** Creates new form deposit */
    public deposit1() {
    	super("Special Order - Deposit");
        initComponents();
        setLocationRelativeTo(null);
        update();
        setTimer();
        getData();
        jProgressBar1.setVisible(false);
    }
    
    private static void createConnection()
    {
        try
        {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            //Get a connection
            conn = DriverManager.getConnection(dbURL); 
        }
        catch (Exception except)
        {
            except.printStackTrace();
        }
    }
    
    private ResultSet getResultSet(String doubt)
    {
        createConnection();
        ResultSet outcome = null;
        try
        {
            stmt = conn.createStatement();
            outcome = stmt.executeQuery(doubt);
        }
        catch (SQLException ex)
        {
        	ex.printStackTrace();
        }
        return outcome;
    }
    
 public void getData(){
    	
    	String Amt = "";
    	int count = 0;
    	
    	 //search for the latest invoice number
       	try
       	{
       	  	String sql;
       	    sql = "SELECT INV_NUM FROM APP.SPECIAL WHERE INV_NUM >= ALL(SELECT INV_NUM FROM APP.SPECIAL)";
       	    
       	   ResultSet rset = getResultSet(sql);
       	    while(rset.next())
       	    {
       	    	count = rset.getInt(1);
       	    	count++;
       	    }
       	    conn.close();
       	}
       	catch(Exception e)
       	{
       	    System.out.println("ERROR : " + e.getMessage());
       	    e.printStackTrace();
       	}  
       	
       	invNum = count - 1;
       	
       	String amtDue = customerDetails.Amt;
       	Double payment = Double.parseDouble(String.valueOf(amtDue));
       	String due = dp.format(payment);
       	total.setText(due);
       	totalAmt = payment;
       	
       	
    	//get the total amount from the current special order
    	/* System.out.println("success");
    	 createConnection();
    	 
    	  String queryString;
    	    queryString = "SELECT SUM(SPECIAL_PRICE) AS TOTAL FROM APP.SPECIAL WHERE INV_NUM="+invNum+"";

    	   // System.out.println(queryString);
    	   ResultSet achieve = getResultSet(queryString);
    	   System.out.println(achieve);

           try
           {
           	  if (achieve.next()) 
           	  {
           		totalAmt = achieve.getDouble("TOTAL");
                System.out.println(totalAmt);
                Amt = dp.format(totalAmt);
            	total.setText(Amt);
           	  }


           }
           catch (SQLException sqlExcept)
           {
               sqlExcept.printStackTrace();
           }*/
           
       
           
    	 
try
{
	System.out.println("success");
    int col0;
    String col1,col2,col3;
    double col4,col5;
    
    
    String queryString1;
    queryString1 = "SELECT SPECIAL_TYPE,SPECIAL_FLAVOR,SPECIAL_SHAPE,SPECIAL_WEIGHT,SPECIAL_PRICE FROM APP.SPECIAL WHERE INV_NUM="+invNum+" ORDER BY SPECIAL_CODE";

   // System.out.println(queryString);
    ResultSet rset = getResultSet(queryString1);

    
    System.out.println(rset);

    int i = 0;
    String price = "";
    
    while(rset.next())
    {
    	col0 = i+1;
    	table.setValueAt(col0, i, 0);
        col1 = rset.getString(1);
        table.setValueAt(col1, i, 1);
        col2 = rset.getString(2);
        table.setValueAt(col2, i, 2);
        col3 = rset.getString(3);
        table.setValueAt(col3, i, 3);
        col4 = rset.getDouble(4);
        table.setValueAt(col4, i, 4);
        col5 = rset.getDouble(5);
        price = dp.format(col5);
        //col5 = Double.parseDouble(price);
        table.setValueAt(price, i, 5);
        
       // invNum = rset.getInt(6);
      // table.insertRow(i, new Object[]{col0,col1,col2,col3,col4,col5,col6});
        i++;
    }
    conn.close();
    
   
    System.out.println(invNum);
}
catch(Exception e)
{
    System.out.println("ERROR : " + e.getMessage());
    e.printStackTrace();
}    	

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jCheckBox1 = new javax.swing.JCheckBox();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        total = new javax.swing.JLabel();
        cash = new javax.swing.JTextField();
        change = new javax.swing.JLabel();
        date = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        deposit = new javax.swing.JTextField();
        pay = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(700, 500));
        getContentPane().setLayout(null);

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "Num", "Cake Type", "Flavour", "Shape", "Weight", "Amt (RM)"
            }
        ));
        jScrollPane1.setViewportView(table);
        table.getColumnModel().getColumn(0).setPreferredWidth(40);
        table.getColumnModel().getColumn(1).setPreferredWidth(120);
        table.getColumnModel().getColumn(4).setPreferredWidth(50);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(80, 130, 530, 100);

        jCheckBox1.setText("Member");
        getContentPane().add(jCheckBox1);
        jCheckBox1.setBounds(80, 80, 100, 22);
        getContentPane().add(jTextField1);
        jTextField1.setBounds(180, 80, 80, 30);

        jButton2.setText("Enter");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(270, 80, 80, 27);

        jLabel4.setText("Member's Name :");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(360, 80, 140, 30);
        getContentPane().add(jTextField2);
        jTextField2.setBounds(500, 80, 110, 30);

        jLabel5.setText("Total Amount    : RM");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(230, 230, 140, 30);

        jLabel6.setText("Deposit             : RM");
        getContentPane().add(jLabel6);
        jLabel6.setBounds(230, 270, 140, 30);

        jLabel7.setText("Cash Received : RM");
        getContentPane().add(jLabel7);
        jLabel7.setBounds(230, 310, 140, 30);

        jLabel8.setText("Change             : RM");
        getContentPane().add(jLabel8);
        jLabel8.setBounds(230, 350, 140, 30);
        getContentPane().add(total);
        total.setBounds(380, 230, 90, 30);
        getContentPane().add(cash);
        cash.setBounds(380, 310, 100, 30);
        getContentPane().add(change);
        change.setBounds(380, 350, 100, 30);
        getContentPane().add(date);
        date.setBounds(485, 40, 160, 20);

        jLabel9.setText("If is a member, please enter member id.                   Date :");
        getContentPane().add(jLabel9);
        jLabel9.setBounds(80, 40, 500, 20);
        getContentPane().add(deposit);
        deposit.setBounds(380, 270, 100, 30);

        pay.setText("PAY");
        pay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                payActionPerformed(evt);
            }
        });
        getContentPane().add(pay);
        pay.setBounds(480, 310, 90, 27);

        jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "DEPOSIT", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 3, 24), new java.awt.Color(44, 42, 225))); // NOI18N
        getContentPane().add(jLabel1);
        jLabel1.setBounds(40, 20, 610, 380);
        getContentPane().add(jProgressBar1);
        jProgressBar1.setBounds(260, 420, 150, 20);

        pack();
    }// </editor-fold>

    private void payActionPerformed(java.awt.event.ActionEvent evt) {
    	
    	String id, invPaid;
    	
    	String Due = total.getText();
    	Double amtDue = Double.parseDouble(String.valueOf(Due));
    	
    	String dep = deposit.getText();
    	String payment = cash.getText();
    	Double depo = Double.parseDouble(String.valueOf(dep));
    	
    	if (depo>amtDue)
    	{
    		JOptionPane.showMessageDialog(null, "DEPOSIT CAN'T EXCEED TOTAL AMOUNT!");
    	}
    		
    	else
    	{
    	if ((dep.equals(""))||(payment.equals("")))
    	{
    		JOptionPane.showMessageDialog(null, "ERROR! CASH PAID OR DEPOSIT CAN'T BE NULL!");
    	}
    	
    	else
    	{
    	depo = Double.parseDouble(String.valueOf(dep));
    	Double pay1 = Double.parseDouble(String.valueOf(payment));
    	Double change1 = pay1 - depo;
    	
    	if (change1<0)
    	{
    		JOptionPane.showMessageDialog(null, "INVALID AMOUNT OF CASH PAID!");
    	}
    	
    	else
    	{
    	change.setText(dp.format(change1));
    	
    	System.out.println(Amt);
    	Double balance = amtDue - depo;

    	
    	if (jTextField1.getText().isEmpty())
        	id = "0";
        
        else
        	id = jTextField1.getText();
    	
    	
    	if (balance == 0.00)
    		invPaid = "Y";
    	else
    		invPaid = "N";
    	
    	//update invoice table
    	 try
    	   	{
    	   		createConnection();
    	   		
    	   		stmt = conn.createStatement();
    	   		String sql1;
    	   	    sql1 = "UPDATE INVOICE SET MEM_ID="+id+",INVL_TOTALCOST="+amtDue+",INV_DEPOSIT="+depo+",INV_PAID='"+invPaid+"' WHERE INV_NUM="+invNum+"";
    	   	    stmt.executeUpdate(sql1);
    	        System.out.println(sql1);
    	   	}
    	   	catch(Exception e)
    	   	{
    	   	    System.out.println("ERROR : " + e.getMessage());
    	   	    e.printStackTrace();
    	   	} 
    	   	
    	
    	jProgressBar1.setValue(100);
        jProgressBar1.setString("Printing...");
        jProgressBar1.setStringPainted(true);
        jProgressBar1.setVisible(true);
        jProgressBar1.setIndeterminate(true);
        
        timer.start();
    	}
    	}
    	}
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    	
    	 System.out.println("success");
    	 createConnection();
    	
    	// jCheckBox1.g
    	String memberId = jTextField1.getText();
        String queryString;
        String memberName = "";
        jTextField2.setText(memberName);

        queryString = "SELECT MEM_NAME FROM APP.MEMBER WHERE MEM_ID ="+memberId+"";

        System.out.println(queryString);
        ResultSet achieve = getResultSet(queryString);

            try
            {
            	  if (achieve.next()) 
            	  {
            		 memberName = (achieve.getString(1));
         
            	  }


            }
            catch (SQLException sqlExcept)
            {
                sqlExcept.printStackTrace();
            }
            
            if (!memberName.equals(""))
            {
            jTextField2.setText(memberName);
            isMember = true;
            }
            
            else
            {
            	 JOptionPane.showMessageDialog(null, "INVALID MEMBER ID!");
            	 jTextField1.setText("-");
            	 isMember = false;
            }
            
            if (isMember==true)
            {
            	total.setText("");
            	Amt = dp.format(0.9*totalAmt);
            	total.setText(Amt);
            	isMember = false;
            }
            
            else
            { 
            	total.setText("");
            	Amt = dp.format(totalAmt);
            	total.setText(Amt);
            	isMember = false;
            	
            }	
    }

     public void setTimer() {
        int messageTimeout = 1000;
        timer1 = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                update();
            }

        });
        timer1.restart();
    }

    public void update() {
        Date currentTime = new Date();

        time++;
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy  hh:mm:ss");
        String dateString = formatter.format(currentTime);

        date.setText(dateString);
        //JOptionPane.showMessageDialog(null, "test3");
    }
    public int time = 0;
    public Timer timer1;
    
    public void stop_timer() {
	    this.setVisible(false);
    	timer.stop();
    }
    private class TimerListener implements ActionListener{
 	   public void actionPerformed(ActionEvent e){
 		   
 	    new Main(Main.col1).setVisible(true);
 	    stop_timer();
 	   } 
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new deposit1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JTextField cash;
    private javax.swing.JLabel change;
    private javax.swing.JLabel date;
    private javax.swing.JTextField deposit;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JButton pay;
    private javax.swing.JTable table;
    private javax.swing.JLabel total;
    // End of variables declaration

}
